package com.summer.dynamicProxy;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibProxy {
	public static <T>T createCglibDynamicProxy(final T obj) throws Exception {
		final Class<?> cls = obj.getClass();
		
		Enhancer enhancer = new Enhancer();//这个事编织器，用来做什么就是做代理外观编织的
		enhancer.setCallback(new CglibInterceptor(obj));
//		enhancer.setInterfaces(cls.getInterfaces());
		enhancer.setSuperclass(cls);
//		enhancer.setClassLoader(cls.getClassLoader());
		@SuppressWarnings("unchecked")
		T cglibProxy = (T) enhancer.create();
		return cglibProxy;
	}

	private static class CglibInterceptor implements MethodInterceptor {

		final Object delegate;//委托人

		CglibInterceptor(Object delegate) {
			this.delegate = delegate;//通过构造注入委托人
		}

		//实现代理方法，因为编织器吧委托人的所有方法都编织好了那些方法会写同样的代码什么代码能就是调用这个方法。
		public Object intercept(Object object, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
			System.out.println("proxy run");

			Object rs = (String) methodProxy.invoke(delegate, objects);
//			if(method.getName().equals("getDataSource"))
//				rs = "我要加密" + rs;
			return rs;
		}
	}
}
